
/**
 * Auto-attach standard client side file input validation.
 */
Drupal.behaviors.filefieldValidateAutoAttach = function(context) {
    $("input[type=file]", context).bind('change', Drupal.filefield.validateExtensions);
};


/**
 * Prevent FileField uploads when using buttons not intended to upload.
 */
Drupal.behaviors.filefieldButtons = function(context) {
    $('input.form-submit', context).bind('mousedown', Drupal.filefield.disableFields);
    $('div.filefield-element input.form-submit', context).bind('mousedown', Drupal.filefield.progressBar);
};

/**
 * Open links to files within the node form in a new window.
 */
Drupal.behaviors.filefieldPreviewLinks = function(context) {
    $('div.filefield-element div.widget-preview a', context).click(Drupal.filefield.openInNewWindow).attr('target', '_blank');
}

/**
 * Admin enhancement: only show the "Files listed by default" when needed.
 */
Drupal.behaviors.filefieldAdmin = function(context) {
    var $listField = $('div.filefield-list-field', context);
    if ($listField.size()) {
        $listField.find('input').change(function() {
            if (this.checked) {
                if (this.value == 0) {
                    $('#edit-list-default-wrapper').css('display', 'none');
                }
                else {
                    $('#edit-list-default-wrapper').css('display', 'block');
                }
            }
        }).change();
    }
};

/**
 * Utility functions for use by FileField.
 * @param {Object} event
 */
Drupal.filefield = {
    validateExtensions: function(event) {
        // Remove any previous errors.
        $('.file-upload-js-error').remove();

        var fieldName = this.name.replace(/^files\[([a-z0-9_]+)_\d+\]$/, '$1');
        var extensions = '';
        if (Drupal.settings.filefield && Drupal.settings.filefield[fieldName]) {
            extensions = Drupal.settings.filefield[fieldName].replace(/[, ]+/g, '|');
        }
        if (extensions.length > 1 && this.value.length > 0) {
            var extensionPattern = new RegExp('\\.(' + extensions + ')$', 'gi');
            if (!extensionPattern.test(this.value)) {
                var error = Drupal.t("The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.",
                        {'%filename': this.value, '%extensions': extensions.replace(/\|/g, ', ')}
                );
                $(this).parent().before('<div class="messages error file-upload-js-error">' + error + '</div>');
                this.value = '';
                return false;
            }
        }
    },
    disableFields: function(event) {
        var clickedButton = this;

        // Only disable upload fields for AHAH buttons.
        if (!$(clickedButton).hasClass('ahah-processed')) {
            return;
        }

        // Check if we're working with an "Upload" button.
        var $enabledFields = [];
        if ($(this).parents('div.filefield-element').size() > 0) {
            $enabledFields = $(this).parents('div.filefield-element').find('input.form-file');
        }
        // Otherwise we're probably dealing with CCK's "Add another item" button.
        else if ($(this).parents('div.content-add-more').size() > 0) {
            $enabledFields = $(this).parent().parent().find('input.form-file');
        }

        var $disabledFields = $('div.filefield-element input.form-file').not($enabledFields);

        // Disable upload fields other than the one we're currently working with.
        $disabledFields.attr('disabled', 'disabled');

        // All the other mousedown handlers (like AHAH) are excuted before any
        // timeout functions will be called, so this effectively re-enables
        // the filefields after the AHAH process is complete even though it only
        // has a 1 millisecond timeout.
        setTimeout(function() {
            $disabledFields.attr('disabled', '');
        }, 1000);
    },
    progressBar: function(event) {
        var clickedButton = this;
        var $progressId = $(clickedButton).parents('div.filefield-element').find('input.filefield-progress');
        if ($progressId.size()) {
            var originalName = $progressId.attr('name');

            // Replace the name with the required identifier.
            $progressId.attr('name', originalName.match(/APC_UPLOAD_PROGRESS|UPLOAD_IDENTIFIER/)[0]);

            // Restore the original name after the upload begins.
            setTimeout(function() {
                $progressId.attr('name', originalName);
            }, 1000);
        }

        // Show the progress bar if the upload takes longer than 3 seconds.
        setTimeout(function() {
            $(clickedButton).parents('div.filefield-element').find('div.ahah-progress-bar').slideDown();
        }, 500);
    },
    openInNewWindow: function(event) {
        window.open(this.href, 'filefieldPreview', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=500,height=550');
        return false;
    }
};
